package game.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Stack;

import javax.swing.JButton;
import javax.swing.JPanel;
import game.code.Loader;

/**
 * extends JPanel. Has-A array of JButton with size of 6
 * Has-A WordFormation
 * handles the events that uses click on button or user cancel (re-enable) a button.
 * 
 * @author Ying
 *
 */
class LetterInventory extends JPanel{
	
	JButton [] buttons ; 
	/**
	 * store the order that the user clicked the buttons
	 */
	Stack<JButton> buttonStack;
	WordFormation wordFormation ;
	
	public LetterInventory(  WordFormation wf ){
		super();
		buttons = new JButton[Loader.KEYWORD_LEN];
		buttonStack = new Stack<JButton>();
		wordFormation = wf ; 
		
		for(int i=0; i<Loader.KEYWORD_LEN; i++){
			buttons[i] = new JButton(" ");
			
			buttons[i].addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					JButton  button = (JButton)e.getSource(); 
					wordFormation.append(button.getText().charAt(0));
					//grey-out a button once clicked
					button.setEnabled(false);
					buttonStack.push(button);
				}
				
			});
			this.add(buttons[i]);
		}
		
		setLayout();
		
		
	}
	
	/**
	 * set the LetterInvetory area layout
	 */
	public void setLayout(){
		
		for(JButton b : buttons){
			b.setPreferredSize( Style.buttonDemention );
			b.setFont(Style.buttonLetterFont);
		}
		
	}

	/**
	 * called after user pressed back_space on keyboard.
	 * using a stack to enable
	 * O(1)
	 */
	public void enableButton( ){

		if(!buttonStack.isEmpty()){
			JButton button = buttonStack.pop();
			button.setEnabled(true);
		}
	}
	
	/**
	 * 
	 * called after user clicked submit on the game UI.
	 */
	public void enableButtons(){
		/*for(int i=0; i<Loader.KEYWORD_LEN; i++)
			buttons[i].setEnabled(true);*/
		while(buttonStack.size()>0){
			buttonStack.pop().setEnabled(true);
		}
	}
	
	/**
	 * upon start the game, load the six lettes into the buttons
	 * @param letters
	 */
	void loadButtons(Collection<Character> letters){
		
		Object [] arr = letters.toArray();
		for(int i=0; i<Loader.KEYWORD_LEN; i++){
			
			buttons[i].setText( ((Character)arr[i]).toString() );
			
		}
		
	}
	
	/**
	 * called when user click the twist button on UI. 
	 */
	void twistButtons(Collection<Character> newLetters){
		wordFormation.removeWord();
		enableButtons();
		loadButtons(newLetters)	;
		
/*		Stack<Character> st = new Stack<Character>();
		while(buttonStack.size()>0){
			st.push(buttonStack.pop().getText().charAt(0));
		}
		
		Object [] arr = newLetters.toArray();
		for(int i=0; i<Loader.KEYWORD_LEN; i++){
			buttons[i].setText( ((Character)arr[i]).toString() );
		}

		while(st.size()>0){
			
			for()
			
			
		}*/

		
	}

	
}
